package com.xinchao.controller;

import com.xinchao.core.constant.BusinessConstant;
import com.xinchao.core.constant.RequestConstant;
import com.xinchao.core.constant.ResponseConstant;
import com.xinchao.core.BaseController;
import com.xinchao.core.constant.BusinessConstant;
import com.xinchao.core.util.HuaWeiCloudUtils;
import com.xinchao.model.User;
import com.xinchao.model.dto.AreaCityDTO;
import com.xinchao.model.sys.JsonResponse;
import com.xinchao.model.vo.DeviceCountVO;
import com.xinchao.service.AreaService;
import com.xinchao.service.DeviceInfoService;
import com.xinchao.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author dxy
 * @date 2018/7/4 19:24
 */
@Controller
@RequestMapping(value = "/web")
public class WebController extends BaseController{
    private static Logger logger = LoggerFactory.getLogger(WebController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private AreaService areaService;

    /**
     * 跳转至登录界面
     */
    @RequestMapping("/login")
    public String goLogin() {
        return "login";
    }

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping("/doLogin")
    public Object login(String userName, String password, HttpServletRequest request) {
        User user = userService.getUserByUserName(userName);
        if (user == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名或密码错误");
        }
        if (BusinessConstant.STATUS_DISABLE == user.getStatus()) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户已被禁用，请联系管理员");
        }
        //验证密码
        if (StringUtils.isBlank(password)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名或密码错误");
        }
        String oldPassword = user.getPassword();
        String md5Password = DigestUtils.md5Hex(password);
        if (!md5Password.equals(oldPassword)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名或密码错误");
        }
        //验证通过，将用户放入sessoin中
        request.getSession().setAttribute(RequestConstant.SESSION_KEY_USER, user);
        return "";
    }

    /**
     * 跳转至index.html
     */
    @RequestMapping(value = "/goIndex")
    public String goIndex(HttpServletRequest request, Model model) {
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        model.addAttribute("userName", loginUser.getUserName());
        //用户所属部门ID
        Long departmentId = loginUser.getDepartmentId();
        //获取部门关联的城市列表
        List<AreaCityDTO> cityList = areaService.listCityByDeparmentId(departmentId);
        model.addAttribute("cityList", cityList);
        model.addAttribute("departmentId", departmentId);
        model.addAttribute("isSuperAdmin", loginUser.getSuperAdminUser());
        if (CollectionUtils.isNotEmpty(cityList)) {
            //把列表第一个作为默认的城市
            String code = cityList.get(0).getCode();
            String cityName = cityList.get(0).getName();
            model.addAttribute("defalutCode", code);
            loginUser.setCityCode(code);
            loginUser.setCityName(cityName);
            request.getSession().setAttribute(RequestConstant.SESSION_KEY_USER, loginUser);
        } else {
            model.addAttribute("defalutCode", "");
            loginUser.setCityCode("");
            loginUser.setCityName("");
            request.getSession().setAttribute(RequestConstant.SESSION_KEY_USER, loginUser);
        }
        return "index";
    }

    /**
     * 注销登录
     */
    @RequestMapping(value = "/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //从session中移除用户
        request.getSession().removeAttribute(RequestConstant.SESSION_KEY_USER);
        //重定向到登录界面
        try {
            response.sendRedirect(request.getContextPath() + "/web/login");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("WebController logout 注销登录失败：" + e.getMessage());
        }
    }

    /**
     * 跳转至home.html
     */
    @RequestMapping(value = "/home")
    public String home(HttpServletRequest request, Model model) {
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        model.addAttribute("userName", loginUser.getUserName());
        String currentCity = getCurrentCityName(request);
        //首页轮询时间(单位：毫秒): 10分钟
        model.addAttribute("timer", BusinessConstant.INDEX_PAGE_COUNT_ROLL_TIMER);
        //统计终端数量
        DeviceCountVO deviceCountVO = deviceInfoService.countByCity(currentCity);
        model.addAttribute("deviceCountVO", deviceCountVO);
        return "home";
    }

    /**
     * 修改登录用户的城市
     */
    @ResponseBody
    @RequestMapping(value = "/updateLoginUserCity")
    public Object updateLoginUserCity(String cityCode, String cityName, HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        loginUser.setCityCode(cityCode);
        loginUser.setCityName(cityName);
        request.getSession().setAttribute(RequestConstant.SESSION_KEY_USER, loginUser);
        return "成功修改登录用户的城市";
    }
}
